package com.jjiang.bbmall.product.exception;

import com.jjiang.common.exception.BizCodeEnumerate;
import com.jjiang.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 集中处理数据校验异常
 */
@ResponseBody
@Slf4j
@RestControllerAdvice(basePackages = "com.jjiang.bbmall.product.controller")
public class BBmallExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();

        // 获取校验的错误结果
        Map<String, String> map = new HashMap<>();
        result.getFieldErrors().forEach((item) -> {
            // FiledError，获取错误提示,错误字段名
            String message = item.getDefaultMessage();
            String filed = item.getField();
            map.put(filed, message);
        });
        return R.error(BizCodeEnumerate.VALID_EXCEPTION.getCode(), BizCodeEnumerate.VALID_EXCEPTION.getMsg()).put("data", map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable) {
        System.out.println(throwable.getMessage());
        return R.error(BizCodeEnumerate.UNKNOWN_EXCEPTION.getCode(), BizCodeEnumerate.UNKNOWN_EXCEPTION.getMsg());
    }
}
